# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/3 13:49 
@Author  : ZhangShenao 
@File    : dict_basic.py 
@Desc    : dict基础

在Python3.7+版本,dict正式被确定为有序
"""

# 以下几种创建dict的方式是等价的
d1 = {'name': 'zsa', 'age': 20, 'hobbies': ['coding', 'reading', 'singing']}
d2 = dict({'name': 'zsa', 'age': 20, 'hobbies': ['coding', 'reading', 'singing']})
d3 = dict([('name', 'zsa'), ('age', 20), ('hobbies', ['coding', 'reading', 'singing'])])
d4 = dict(name='zsa', age=20, hobbies=['coding', 'reading', 'singing'])
print(d1 == d2 == d3 == d4)  # True

# dict可以通过key访问value,如果key不存在,会抛出KeyError异常
print(d1['name'])  # zsa
# print(d1['gender'])  # KeyError: 'gender'

# dict可以通过get()函数来访问value
v1 = d1.get('name')
print(f'v1 = {v1}')  # v1 = zsa
# 如果key不存在,会返回None
v2 = d1.get('gender')
print(f'v2 = {v2}')  # v2 = None
# 可以指定一个默认值,当key不存在时返回默认值
v3 = d1.get('gender', 'unknown')
print(f'v3 = {v3}')  # v3 = unknown

# 可以通过in关键字来判断key是否存在于dict中
print(f'name is in d1: {'name' in d1}')  # True
print(f'gender is in d1: {'gender' in d1}')  # False

# dict是mutable的,可以进行增删改操作
user = {'name': 'zsa', 'age': 20}
# 增加key-value
user['gender'] = 'male'
user['birthday'] = '1990-01-01'
# 修改key-value
user['age'] = 21
# 删除key-value
del user['name']
print(user)

# 可以使用sorted()函数对dict进行排序,返回一个排好序的list,list中的元素为dict的key和value组成的二元tuple
words = {'d': 2, 'a': 3, 'b': 5, 'c': 1}
sort_word_by_key = sorted(words.items(), key=lambda x: x[0], reverse=False)
sort_word_by_value = sorted(words.items(), key=lambda x: x[1], reverse=False)
print(f'sort_word_by_key = {sort_word_by_key}')  # sort_word_by_key = [('a', 3), ('b', 5), ('c', 1), ('d', 2)]
print(f'sort_word_by_value = {sort_word_by_value}')  # sort_word_by_value = [('c', 1), ('d', 2), ('a', 3), ('b', 5)]
